<?php
namespace App\Libraries\Tools;


use App\Models\Shop\ShopManager;
use App\Models\User\User;
use App\Models\User\UserPoint;
use App\Models\User\UserPwLock;
use Illuminate\Support\Facades\Auth;

class CheckAuth
{

    /**
     * 判断是否经理
     * @param $shop_id
     * @param int $user_id
     * @param bool $exist 判断是否存在记录
     * @return bool
     */
    public static function checkIfManager($shop_id, $user_id=0, $exist=false){
        $shopManager = new ShopManager();
        if(empty($user_id)){
            $user_id = Auth::id();
        }
        $sql = $shopManager->where('user_id', $user_id)
            ->where('shop_id', $shop_id);
        if(!$exist){
            $sql = $sql->where('status', 1);
        }
        $shopManager = $sql->first();
        if(empty($shopManager)){
            return false;
        }
        return true;
    }

    /**
     * 判断是否店主
     * @param $user_id
     * @param ShopManager $shopManager
     * @return ShopManager|null
     */
    public static function checkIfOwner($user_id, ShopManager $shopManager){
        $shopManager = $shopManager->where('user_id', $user_id)
            ->where('status', 1)
            ->where('level', 1)
            ->first();
        if(empty($shopManager)){
            return null;
        }
        return $shopManager;
    }

    /**
     * 判断是否为有效用户
     * @param $user_id
     * @return bool
     */
    public static function checkIfValidUser($user_id){
        $user = new User();
        $user = $user->where('user_id', $user_id)->where('status', 1)
            ->where('is_bot', 0)->where('is_guest', 0)->first();
        if(empty($user)){
            return false;
        }
        return true;
    }

    /**
     * 检查支付密码
     * @param User $user
     * @param $pw
     * @return int
     */
    public static function checkPaymentPw(User $user, $pw){
        if(empty($user->payment_pw)){
            return 40106;
        }
        $pw_lock = UserPwLock::where('user_id', $user->user_id)->first();
        if(!empty($pw_lock) && $pw_lock->payment_pw >= 3){
            return 40107;
        }

        if(!password_verify($pw, $user->payment_pw)){
            if(empty($pw_lock)){
                $pw_lock = new UserPwLock();
                $pw_lock->payment_pw = 1;
                $pw_lock->user_id = $user->user_id;
                $pw_lock->save();
            }else{
                $pw_lock->increment('payment_pw');
            }
            return 40105;
        }
        return 200;
    }

    /**
     * 检查用户等级
     * @param $user
     * @param $level
     * @return int
     */
    public static function checkWithdrawLevel($user, $level){
        $point = UserPoint::where('user_id', $user->user_id)->first()->total_point??0;
        if(Point::getLevel($point) < $level && $user->vip_level != 2){
            return 40101;
        }
        return 200;
    }
}